package com.dwzlab.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;

/**
 * @author zhuxiaodong
 *
 */
public class FileuploadAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DiskFileUpload dfu = new DiskFileUpload();
		String filename = "";
		try {
			@SuppressWarnings("unchecked")
			List<FileItem> items = dfu.parseRequest(request);
			for(FileItem item : items){
				if(!item.isFormField()){
					filename = item.getName();
					break;
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		response.setContentType("text/html;charset=utf-8");
		String str ="{\"id\":\"1000\"," +
				"\"fileName\":\""+filename+"\"," +
				"\"attachmentPath\":\"/upload/"+filename+"\"," +
				"\"attachmentSize\":\"1024\"}";
		
		System.out.println(str);
		response.getWriter().write(str);
	}

}
